/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.reserve;

import java.util.Collection;

import static jp.aist.gtrc.plus.reserve.ReserveStatus.State.*;

class AbortOperator extends TwoPhaseOperator {

	AbortOperator(ReserveManager rsvMgr) {

		super(rsvMgr);

	}

	protected void recoverReallocated(ReserveInfo target, Collection<ReserveInfo> reallocated) {

		if (reallocated == null) {
			return;
		}

		for (ReserveInfo r : reallocated) {
			if (r == target) {
				continue;
			}
			try {
				r.recoverReservedNodes();
				recorder.store(r);
			} catch (ReserveException e) {
				// ignore exception to continue
				logger.debug("recover reallocated failed", e);
			}
		}

	}

	protected void recoverReserveInfo(ReserveOperation ope) {

		ReserveInfo target = ope.getTargetReserveInfo();
		if (target == null) {
			return;
		}

		recoverReallocated(target, ope.getReallocatedReserveInfos());

		target.clearWaitCommit();

		try {
			switch(ope.getOperationType()) {
			case reserve:
				rsvMgr.removeReserveInfo(target, true);
				break;
			case modify:
			case cancel:
				target.recoverModification();
				target.setReserveState(Confirmed);
				recorder.store(target);
				break;
			case destroy:
				target.recoverModification();
				// TODO state may be 'Canceled'!
				target.setReserveState(Confirmed);
				rsvMgr.addNewReserveInfo(target);
				break;
			case remove:
				assert(false);
				break;
			default:
				assert(false);
				logger.debug("program error: not supported to abort " + ope);
				break;
			}
		} catch (ReserveException e) {
			// ignore exception to continue
			logger.debug("recover modification failed", e);
		}

	}

	final void abort(ReserveId rsvId) throws ReserveException {

		logger.debug("Try abort : " + rsvId);

		checkCommitAbort(rsvId);

		ReserveOperation ope = getCurrentOperation();
		if (ope.isAbortable() == false) {
			// To cancel running reserve is not abortable...
			throw new ReserveException("This transaction is not abortable. Use commit.");
		}

		try {
			recorder.rollback();
		} catch (ReserveException e) {
			// ignore
		}

		recoverReserveInfo(ope);

		done();
		logger.debug("aborted");

	}

}
